package com.kyz.launcherapp.fragments

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DefaultItemAnimator
import com.iflytek.cyber.iot.show.core.launcher.LauncherDataHelper
import com.iflytek.cyber.iot.show.core.launcher.LauncherMemory
import com.kyz.launcherapp.BuildConfig
import com.kyz.launcherapp.R
import com.kyz.launcherapp.adapter.AppAdapter
import com.kyz.launcherapp.base.BaseSupportFragment
import com.kyz.launcherapp.base.BaseSwipeBackFragment
import com.kyz.launcherapp.installapp.AppData
import com.kyz.launcherapp.installapp.TemplateAppData
import com.kyz.launcherapp.utils.OnItemClickListener
import com.weikaiyun.fragmentation.SwipeBackLayout
import kotlinx.android.synthetic.main.fragment_apps.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


class AppsFragment : BaseSwipeBackFragment() {
    override fun getLayoutId(): Int = R.layout.fragment_apps
    private lateinit var adapter: AppAdapter
    private var launcherDataHelper: LauncherDataHelper? = null


    companion object {
        /** 位于黑名单中的包名不予显示 **/
        private val blackPartyAppArray = arrayOf(
            BuildConfig.APPLICATION_ID,
            "com.android.documentsui",
            "com.android.quicksearchbox",
            "com.android.contacts",
            "com.android.camera2",
            "com.android.soundrecorder",
            "com.android.calendar",
            "com.android.apkinstaller",
            "com.android.rk",
            "com.android.gallery3d",
           // "com.android.settings",
            "acr.browser.barebones",
            "com.android.calculator2",
            "com.android.email",
            "com.android.music",
            "com.android.deskclock",
            "com.android.traceur",
            "android.rk.RockVideoPlayer",
            "org.chromium.webview_shell",
        )
        private val privateSortedApps = arrayOf(
            "com.qiyi.video.speaker",
            "com.dianshijia.newlive"
        )
    }

    private val packageReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            Thread {
                postAppUpdated()
            }.start()
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_PACKAGE_ADDED)
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED)
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED)
        filter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED)
        filter.addDataScheme("package")
        context?.registerReceiver(packageReceiver, filter)
    }

    override fun onStart() {
        super.onStart()
        Thread {
            val context = context ?: return@Thread
            launcherDataHelper = LauncherDataHelper(context)
            if (LauncherMemory.partyApps == null && LauncherMemory.privateApps == null) {
                val appsForDb = launcherDataHelper?.queryPartyApps()
                if (!appsForDb.isNullOrEmpty()) {
                    recycler_view.post {
                        setAppDataToAdapter(appsForDb)
                    }
                }
            }

            if (LauncherMemory.templateApps == null) {
                val templateAppsForDb = launcherDataHelper?.queryTemplateApps()

                if (!templateAppsForDb.isNullOrEmpty()) {
                    recycler_view.post {
                        setTemplateAppToAdapter(templateAppsForDb)
                        LauncherMemory.templateApps = templateAppsForDb
                    }
                }
            }
            postAppUpdated()
        }.start()
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        back.setOnClickListener {
            pop()
        }
        setRecyclerView()
        super.initView(view, savedInstanceState)
    }

    private fun setRecyclerView() {
        adapter = AppAdapter()
        LauncherMemory.partyApps.takeUnless { it.isNullOrEmpty() }?.let {
            adapter.setPartyAppData(it)
        }
        LauncherMemory.templateApps.takeUnless { it.isNullOrEmpty() }?.let {
            adapter.setTemplateAppData(it)
        }
        LauncherMemory.privateApps?.takeUnless { it.isNullOrEmpty() }?.let {
            adapter.setPrivateAppData(it)
        }
        adapter.onItemClickListener = object : OnItemClickListener {
            override fun onItemClick(parent: ViewGroup, itemView: View, position: Int) {
                adapter.getAppData(position)?.let {
                    when (it.appType) {
                        AppData.TYPE_TEMPLATE -> {

                        }
                        AppData.TYPE_PARTY -> {
                            context?.packageManager?.getLaunchIntentForPackage(it.packageName)
                                ?.let { intent ->
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                    startActivity(intent)
                                }
                        }
                        AppData.TYPE_INTERNAL -> {

                        }
                        else -> {
                        }
                    }
                }
            }
        }
        recycler_view.itemAnimator = DefaultItemAnimator()
        recycler_view.adapter = adapter
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.d("TAG1", "AppsFragment  onCreateView:.... ")
        return super.onCreateView(inflater, container, savedInstanceState)
    }


    private fun postAppUpdated() {
        val packageManager = context?.packageManager ?: return
        val packages = packageManager.getInstalledPackages(0)
        val apps = mutableListOf<AppData>()
        packages.forEach {
            if (!blackPartyAppArray.contains(it.packageName)
                && packageManager.getLaunchIntentForPackage(it.packageName) != null
                && (packageManager.getApplicationEnabledSetting(it.packageName) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                        || packageManager.getApplicationEnabledSetting(it.packageName) == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
            ) {
                apps.add(
                    AppData(
                        it.applicationInfo.loadLabel(packageManager).toString(),
                        it.packageName,
                        packageManager.getApplicationIcon(it.packageName)
                    )
                )
            }
        }

        recycler_view.post {
            setAppDataToAdapter(apps)
        }
    }


    private fun setAppDataToAdapter(apps: List<AppData>) {
        val oldSize = adapter.itemCount
        val oldPackages = mutableListOf<String>()
        for (i in 0 until adapter.itemCount) {
            adapter.getAppData(i)?.let {
                oldPackages.add(it.packageName)
            }
        }
        setPartyAppToAdapter(apps)

        val newSize = adapter.itemCount
        val newPackages = mutableListOf<String>()
        for (i in 0 until adapter.itemCount) {
            adapter.getAppData(i)?.let {
                newPackages.add(it.packageName)
            }
        }

        if (newSize - oldSize == 1 || oldSize - newSize == 1) {
            val isAdded = newSize > oldSize
            for (i in 0 until oldPackages.size) {
                if (i < newPackages.size) {
                    if (oldPackages[i] != newPackages[i]) {
                        if (isAdded) {
                            adapter.notifyItemInserted(i)
                            break
                        } else {
                            adapter.notifyItemRemoved(i)
                            break
                        }
                    }
                } else {
                    if (!isAdded) {
                        adapter.notifyItemRemoved(i)
                        break
                    }
                }
            }
        } else {
            when {
                newSize > oldSize -> {
                    if (oldSize > 4)
                        adapter.notifyItemRangeChanged(4, oldSize)
                    adapter.notifyItemRangeInserted(oldSize, newSize - oldSize)
                }
                newSize == oldSize -> {
                    if (oldSize > 4)
                        adapter.notifyItemRangeChanged(4, oldSize)
                }
                else -> {
                    if (newSize > 4)
                        adapter.notifyItemRangeChanged(4, newSize)
                    adapter.notifyItemRangeRemoved(newSize, oldSize - newSize)
                }
            }
        }
    }

    private fun setPartyAppToAdapter(apps: List<AppData>) {
        val privateApps = mutableListOf<AppData>()
        val partyApps = mutableListOf<AppData>()

        privateSortedApps.map { packageName ->
            apps.map { appData ->
                if (appData.packageName == packageName) {
                    privateApps.add(appData)
                }
            }
        }
        apps.map { appData ->
            var shouldNotAdd = false
            privateSortedApps.map { packageName ->
                if (appData.packageName == packageName) {
                    shouldNotAdd = true
                }
            }
            if (!shouldNotAdd) {
                partyApps.add(appData)
            }
        }

        LauncherMemory.partyApps = partyApps
        LauncherMemory.privateApps = privateApps

        adapter.setPrivateAppData(privateApps)
        adapter.setPartyAppData(partyApps)
    }

    private fun setTemplateAppToAdapter(apps: List<TemplateAppData>) {
        apps.distinctBy { it.name } //去重

        adapter.setTemplateAppData(apps)

        val memoryTemplateApps = LauncherMemory.templateApps
        if (memoryTemplateApps.isNullOrEmpty()) {
            adapter.notifyItemRangeInserted(6, apps.size)
        } else {
            val oldSize = memoryTemplateApps.size
            val newSize = apps.size
            if (oldSize <= newSize) {
                adapter.notifyItemRangeChanged(6, oldSize)
                if (oldSize != newSize)
                    adapter.notifyItemRangeInserted(
                        6 + oldSize,
                        newSize - oldSize
                    )
            } else {
                adapter.notifyItemRangeChanged(6, newSize)
                adapter.notifyItemRangeRemoved(6 + newSize, oldSize - newSize)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        Log.d("TAG1", "AppsFragment  onPause:.... ")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("TAG1", "AppsFragment onDestroy:.... ")
    }

    override fun onResume() {
        super.onResume()
        Log.d("TAG1", "AppsFragment onResume:.... ")
    }

    override fun onBackPressedSupport(): Boolean {
        Log.d("TAG1", "AppsFragment onBackPressedSupport:.... ")
        return super.onBackPressedSupport()
    }
}